# -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name： __init__.py
Description :
Author : 'li'
date： 2020/11/5
-------------------------------------------------
Change Activity:
2020/11/5:
-------------------------------------------------
"""
import cv2
import numpy as np

from ml.cv.util.distance import get_distance


def __get_area_shape(bbox):
    """
    get area shape
    :param bbox:
    :return:
    """
    len_1, len_2, len_3, len_4 = get_distance(bbox[0], bbox[1]), get_distance(bbox[1], bbox[2]), \
                                 get_distance(bbox[2], bbox[3]), get_distance(bbox[3], bbox[0])
    tmp_width_max = int(max(len_1, len_3))
    tmp_height_max = int(max(len_4, len_2))
    is_horizontal = tmp_width_max > tmp_height_max
    if is_horizontal:
        return tmp_width_max, tmp_height_max
    return tmp_width_max, tmp_height_max


def clip_text_area(bbox, original_image):
    """
    get text area
    """
    area_width, area_height = __get_area_shape(bbox)
    if area_width < 6 or area_height < 6:
        return None, None
    pts1 = np.float32([bbox[0], bbox[1], bbox[3], bbox[2]])
    pts2 = np.float32([[0, 0], [0, area_width], [area_height, 0], [area_height, area_width]])
    transform = cv2.getPerspectiveTransform(pts1, pts2)
    dst = cv2.warpPerspective(original_image, transform, (area_height, area_width))
    dst = np.rot90(dst)
    dst = np.flip(dst, axis=0)
    return dst, bbox
